package com.hulk.dryad.manage.config;

import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.Ordered;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;


import java.util.Collections;

/**
 * 处理跨域访问
 * @author hulk
 */
@Configuration(proxyBeanMethods = false)
public class CorsConfig  {

	private static  final  String CORS_BEAN_NAME = "crossOriginFilter";

	@Primary
	@Bean
	public FilterRegistrationBean<CorsFilter> crossOriginFilter() {
		CorsConfiguration corsConfiguration = new CorsConfiguration();
		//1,允许任何来源
		corsConfiguration.setAllowedOriginPatterns(Collections.singletonList(CorsConfiguration.ALL));
		//2,允许任何请求头
		corsConfiguration.addAllowedHeader(CorsConfiguration.ALL);
		//3,允许任何方法
		corsConfiguration.addAllowedMethod(CorsConfiguration.ALL);
		//4,允许凭证
		corsConfiguration.setAllowCredentials(true);

		corsConfiguration.setMaxAge(3600L);

		UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
		source.registerCorsConfiguration("/**", corsConfiguration);
		FilterRegistrationBean<CorsFilter> corsBean = new FilterRegistrationBean<>(new CorsFilter(source));
		corsBean.setName(CORS_BEAN_NAME);
		//这个顺序也有可能会有影响，尽量设置在前面
		corsBean.setOrder(Ordered.HIGHEST_PRECEDENCE);
		return corsBean;
	}


} 